/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.designless.business.dao;

import br.com.designless.business.entity.FutibaManagerEntity;
import br.com.designless.util.Constantes;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author diogenes.feijo
 */
@Stateless(name=DAOLocal.JNDI_NAME)
public class DAOBean<T extends FutibaManagerEntity> implements DAOLocal<T> {

    @PersistenceContext(name=Constantes.PERSISTENCE_UNIT_NAME)
    private EntityManager entityManager;

    public T salvar(T t) {
        return entityManager.merge(t);
    }

    public void excluir(T t) {
        T managed = buscar(t.getClass(), t.getPk());
        
        entityManager.remove(managed);
    }

    public T buscar(Class classe, Serializable i) {
        return (T) entityManager.find(classe, i);
    }

    public List<T> buscar(String namedQuery, Map<String, Object> parametros) {
        Query query = entityManager.createNamedQuery(namedQuery);

        if (parametros != null) {
            Iterator<Map.Entry<String, Object>> it = parametros.entrySet().iterator();

            while (it.hasNext()) {
                Map.Entry parametro = it.next();

                query.setParameter(parametro.getKey().toString(), parametro.getValue());
            }
        }

        return query.getResultList();
    }

}